#pragma once

#include "BaseNetworkChannel.h"
#include <asio.hpp>

namespace SeanNetwork {

/**
 * @brief TCP channel implementation.
 * 
 * Provides TCP-specific network channel implementation by extending
 * the BaseNetworkChannel template methods.
 */
class TcpChannel : public BaseNetworkChannel {
public:
    TcpChannel(asio::io_context& ioContext);
    ~TcpChannel() override;
    
    // INetworkChannel interface implementation
    bool Initialize() override;
    bool Connect(const std::string& host, uint16_t port) override;
    void Disconnect() override;
    bool SendMsg(std::shared_ptr<NetworkMessage> message) override;
    void SetMessageCallback(MessageReceiveCallback callback) override;
    void SetConnectionCallback(ConnectionStateCallback callback) override;
    ConnectionState GetConnectionState() const override;
    NetworkStats GetNetworkStats() const override;
    uint32_t GetLatency() const override;
    void Update() override;
    ChannelType GetChannelType() const override;
    
    // TCP specific methods
    void SetKeepAliveInterval(uint32_t intervalMs);
    void SetReconnectStrategy(uint32_t initialDelayMs, uint32_t maxDelayMs, uint32_t maxAttempts);
    
protected:
    // BaseNetworkChannel template methods implementation
    bool DoInitialize() override;
    bool DoConnect(const std::string& host, uint16_t port) override;
    void DoDisconnect() override;
    void DoSendMessage(std::shared_ptr<NetworkMessage> message) override;
    void DoUpdate() override;
    void StartReconnect() override;
    void SendKeepAlive() override;
    
    // Helper methods from base class
    void UpdateConnectionState(ConnectionState newState, const std::string& reason = "");
    void UpdateNetworkStats(uint64_t bytesSent, uint64_t bytesReceived, bool messageSent, bool messageReceived);
    void UpdateRtt(uint32_t rtt);
    uint32_t CalculateReconnectDelay() const;
    void HandleMessageAck(uint32_t messageId, bool success);
    
private:
    asio::ip::tcp::socket m_Socket;
    asio::ip::tcp::endpoint m_Endpoint;
    
    std::vector<uint8_t> m_ReadBuffer;
    uint32_t m_HeaderSize;
    
    uint32_t m_KeepAliveInterval;      // 心跳包间隔（毫秒）
    
    std::shared_ptr<asio::steady_timer> m_KeepAliveTimer;
    std::shared_ptr<asio::steady_timer> m_ReconnectTimer;
    
    // TCP specific methods
    void StartReceive();
    void ReadHeader();
    void ReadBody(uint32_t messageLength);
    void SendNextMessage();
    
    // 处理完整消息
    void HandleCompleteMessage(uint32_t messageLength);
};

} // namespace SeanNetwork
